{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'''\n",
    "1.彩色图像到灰色图像的转换\n",
    "2.将图片分割为若干个小方块，并计算其灰度值\n",
    "3.将0-255的灰度值划分为n个范围，并将第二步的结果映射到该范围内\n",
    "4.相应灰度段中的像素个数统计\n",
    "5.统计的平均值代替原来的结果\n",
    "'''\n",
    "import cv2\n",
    "import numpy as np\n",
    "img = cv2.imread('image00.jpg',1)\n",
    "imgInfo = img.shape\n",
    "height = imgInfo[0]\n",
    "width = imgInfo[1]\n",
    "gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "dstImg = np.zeros((height,width,3),np.uint8)\n",
    "# 将灰度等级划分为8个范围\n",
    "for i in range(4,height-4):\n",
    "    for j in range(4,width-4):\n",
    "        array1 = np.zeros(8,np.uint8)\n",
    "        for m in range(-4,4):\n",
    "            for n in range(-4,4):\n",
    "                # 统计灰度段内的像素个数 256/8=32\n",
    "                p1 = int(gray[i+m,j+n]/32)\n",
    "                array1[p1] = array1[p1]+1\n",
    "        currentMax = array1[0]\n",
    "        l = 0\n",
    "        # 获取像素最多的灰度段currentMax和下标k\n",
    "        for k in range(0,8):\n",
    "            if currentMax<array1[k]:\n",
    "                currentMax = array1[k]\n",
    "                l = k\n",
    "        for m in range(-4,4):\n",
    "            for n in range(-4,4):\n",
    "                if gray[i+m,j+n]>(l*32) and gray[i+m,j+n]<=((l+1)*32):\n",
    "                    (b,g,r) = img[i+m,j+n]\n",
    "        dstImg[i,j] = (b,g,r)\n",
    "cv2.imshow('img',img)\n",
    "cv2.imshow('dstImg',dstImg)  \n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
